import { LinRouter, NotFound } from 'lin-mizar';
import { ContentDao } from '../../dao/content';
import { PositiveIdValidator } from '../../validator/common';
import { groupRequired } from '../../middleware/jwt';
import {
  ContentSearchValidator,
  CreateOrUpdateContentValidator
} from '../../validator/content';
const { Content } = require('../../model/content');
const { getSafeParamId } = require('../../lib/util');

const contentApi = new LinRouter({
  prefix: '/v1/content',
  module: '文章'
});

// content 的dao 数据库访问层实例
const contentDto = new ContentDao();

contentApi.get('/:id', async ctx => {
  const v = await new PositiveIdValidator().validate(ctx);
  const id = v.get('path.id');
  const content = await contentDto.getContent(id);
  if (!content) {
    throw new NotFound({
      code: 10022
    });
  }
  ctx.json(content);
});

contentApi.get('/', async ctx => {
  const contents = await contentDto.getContents();
  if (!contents) {
    throw new NotFound({
      code: 10022
    });
  }
  ctx.json(contents);
});

contentApi.post('/', async ctx => {
  const v = await new CreateOrUpdateContentValidator().validate(ctx);
  await contentDto.createContent(v);
  ctx.success({
    code: 12
  });
});

// contentApi.delete('/:id', async ctx => {
//   const v = await new PositiveIdValidator().validate(ctx);
//   const id = v.get('path.id');
//   const content = await contentDto.getContent(id);
//   if (!content) {
//     throw new NotFound({
//       code: 10022
//     });
//   }
//   ctx.json(content);
// });

contentApi.linDelete(
  'deleteContent',
  '/:id',
  contentApi.permission('删除文章'),
  groupRequired,
  async ctx => {
    const v = await new PositiveIdValidator().validate(ctx);
    const id = v.get('path.id');
    await contentDto.deleteContent(id);
    ctx.success({
      code: 14
    });
  }
);

export { contentApi };